﻿using System;
using System.Timers;
using System.Net.Mail;

namespace Sustainalytics.PregenerateScreeningReports.Service
{
    class TTLManager
    {
        static Timer _timer;
        static string _machineName;
        static bool _executeShutdown;
        static int _shutdownDelaySeconds;
        static string _emailFrom;
        static string _emailTo;


        public static void Init(string machineName, bool executeShutdown, string emailFrom, string emailTo, int shutdownDelaySeconds)
        {
            _shutdownDelaySeconds = shutdownDelaySeconds;
            _executeShutdown = executeShutdown;
            _emailFrom      = emailFrom;
            _emailTo        = emailTo;
            _machineName    = machineName;
             Update(TimeSpan.FromMinutes(55));
        }
        public static void  Update(TimeSpan maximumDuration)
        {
            if (_timer != null)            
                _timer.Stop();
           
            
            var now             = DateTime.Now;
            var systemStart     = now.Subtract(TimeSpan.FromMilliseconds(System.Environment.TickCount));
            var shutdownTime    = systemStart.Add(maximumDuration);
            var tillShutdown    = (shutdownTime - now).TotalMilliseconds;


            if (now >= shutdownTime)
            {
                if (_executeShutdown)
                    Shutdown();
            }
            else
            {
                PSREventSource.Log.ShutdownScheduledOn(shutdownTime.ToString("s"));
                _timer = new Timer(tillShutdown);
                _timer.Elapsed += (o, e) => Shutdown();
                _timer.Start();
            }
        }
        public static void Shutdown()
        {
            PSREventSource.Log.Shutdown();
            try
            {
                SendLifeTimeEmail(_machineName);
            }
            catch (Exception ex)
            {
                PSREventSource.Log.Exception(ex);
            }
            if (_executeShutdown && !Environment.UserInteractive)
                System.Diagnostics.Process.Start("shutdown", "/s /t " + _shutdownDelaySeconds.ToString());
        }

        private static void SendLifeTimeEmail(string machine)
        {
            try 
            {
                var systemStart     = DateTime.Now.Subtract(TimeSpan.FromMilliseconds(System.Environment.TickCount));
                var duration        = (DateTime.Now - systemStart).Add(TimeSpan.FromSeconds(90));
                using (var mailClient = new SmtpClient())
                using (var mailMsg = new MailMessage())
               
                {
                    mailMsg.To.Add(new MailAddress(_emailTo));
                    mailMsg.From = new MailAddress(_emailFrom);
                    mailMsg.Subject = machine + " lifetime report";
                    mailMsg.Body = string.Format("{2}\t{0} was running for {1}, starting at {3} .{2}{2}\tRegards, GA",
                                        machine, duration.ToString(@"hh\:mm\:ss"), Environment.NewLine, systemStart.ToString("s"));
                    mailClient.Send(mailMsg);
                }
            }
            catch(Exception ex)
            {
                PSREventSource.Log.Exception(ex);
            }
        }


    }
}
